﻿using Coldairarrow.Util;
using Coldairarrow.Util.DTO.OnlineChat;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;


namespace Coldairarrow.Business
{
    public class MessageHub : Hub
    {
        private readonly IHubContext<MessageHub> _messageHub;
        readonly IServiceProvider _serviceProvider;
        public MessageHub( IServiceProvider serviceProvider, IHubContext<MessageHub> messageHub)
        {
            _serviceProvider = serviceProvider;
            _messageHub = messageHub;
        }

        /// <summary>
        /// 客户端调用方法
        /// </summary>
        /// <param name="resiverId">接收者Id</param>
        /// <param name="count">未读消息个数</param>
        /// <returns></returns>
        public  Task SendMessage(string resiverId, int count)
        {
            //服务端返回时调用方法
            return Clients.All.SendAsync(resiverId, count);

        }

        private async Task SendData(string id, int count)
        {
           await  Clients.Client(id).SendAsync("unread", count);
        }

        public async Task SendsData(string id, int count)
        {
            await Clients.All.SendAsync("unread", count);
        }

        public Task SendMessageToCaller(string message)
        {
            return Clients.Caller.SendAsync("ReceiveMessage", message);
        }

        /// <summary>
        /// 分组获取消息
        /// </summary>
        /// <param name="roleId">角色Id(分组Id)</param>
        /// <param name="count">未读消息个数</param>
        /// <returns></returns>
        public Task SendMessageToGroup(string roleId, int count)
        {

             return Clients.Group(roleId).SendAsync("unread", count);
        }


        ///// <summary>
        ///// 添加用户
        ///// </summary>
        ///// <param name="groupName"></param>
        //public void AddUser(string groupName)
        //{
        //    string connid = Context.ConnectionId;
        //    if (!groupName.IsNullOrEmpty())
        //    {
        //        Groups.AddToGroupAsync(connid, groupName);
        //        var cache = _serviceProvider.GetService<IDistributedCache>();
        //        cache.SetString("UserList", "0");
        //    }
        //}

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="type"></param>
        /// <param name="classId"></param>
        /// <param name="state"></param>
        public void AddUser(string userId, int type, int classId)
        {
            string connid = Context.ConnectionId;
            Log.Information("连接参数UId => userId:{0}", userId);
            Log.Information("连接参数Type => type:{0}", type);
            Log.Information("连接参数ClassId => classId:{0}", classId);

            #region//获取在线人员
            var uList = new List<OnLinkUserDTO>();
            var cache = _serviceProvider.GetService<IDistributedCache>();
            var jstr = cache.GetString("OLinkUserList");
            if (!jstr.IsNullOrEmpty())
            {
                if (!jstr.Contains("{"))
                {
                    jstr ="";
                    cache.SetString("OLinkUserList", jstr);
                }
                else
                {
                    uList = JsonConvert.DeserializeObject<List<OnLinkUserDTO>>(jstr);
                } 
            }
            #endregion

            #region//登录人员插入登录用户/客服分组
            if (!userId.IsNullOrEmpty())
            {
                var groupName = "";
                if (type == 0)
                {
                    groupName = "USE" +userId;//用户
                }
                else
                {
                    groupName = "CS" +userId; //客服
                }

                OLCSUserList.OLUList = OLCSUserList.OLUList.IsNullOrEmpty() ? new List<OnLinkUserDTO>() : OLCSUserList.OLUList;
                var aCount =  OLCSUserList.OLUList.Where(x => x.Connid.Equals(connid) && x.GroupName.Equals(groupName)).Count();
                if (aCount == 0)
                {
                    if (!userId.IsNullOrEmpty())
                    {
                        //新增在线人员
                        Groups.AddToGroupAsync(connid, groupName);

                        OnLinkUserDTO model = new OnLinkUserDTO();
                        model.UserId = userId;
                        model.Connid = connid;
                        model.UserType = type;
                        model.Class = classId;
                        model.GroupName = groupName;
                        model.CreateTime = DateTime.Now;

                        OLCSUserList.OLUList.Add(model);

                        if (classId >= 0)
                        {
                            var bCount = uList.Where(x => x.Connid.Equals(connid) && x.GroupName.Equals(groupName)).Count();
                            if (bCount == 0)
                            {
                                uList.Add(model);

                                //新用户缓存
                                cache.SetString("OLinkUserList", uList.ToJson().ToString());
                            }                           
                        }
                        else
                        {
                            var bModel = uList.Where(x => x.Connid.Equals(connid) && x.GroupName.Equals(groupName)).FirstOrDefault();
                            if (!bModel.IsNullOrEmpty())
                            {
                                uList.Remove(bModel);

                                //新用户缓存
                                cache.SetString("OLinkUserList", uList.ToJson().ToString());
                            }
                        }
                    }
                }
            }
            #endregion

            //所有人插入普通用户分组
            if (type == 0)
            {
                var aCount = uList.Where(x => x.Connid.Equals(connid) && x.UserId.Equals("")).Count();
                if (aCount == 0)
                {
                    //新增所有前台用户—发送通知使用
                    OnLinkUserDTO model = new OnLinkUserDTO();
                    model.UserId = "";
                    model.Connid = connid;
                    model.UserType = type;
                    model.Class = classId;
                    model.CreateTime = DateTime.Now;
                    model.GroupName = "VSP"; //用户
                    Groups.AddToGroupAsync(connid, model.GroupName);
                    uList.Add(model);
                    //插入新用户
                    cache.SetString("OLinkUserList", uList.ToJson().ToString());
                }
            }
        }

        /// <summary>
        /// 连接后方法
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            string connid = Context.ConnectionId;
            Log.Information("链接进入！cId:{0}", connid);
            var http = Context.GetHttpContext();

            var userId = http.Request.Query["userId"];
            var type = http.Request.Query["type"];
            var classId = http.Request.Query["classId"];

            Log.Information("参数UId => userId:{0}", userId);
            Log.Information("参数TP => type:{0}", type);
            Log.Information("参数TP => classId:{0}", classId);
            if (!userId.IsNullOrEmpty() && !type.IsNullOrEmpty() && userId != "undefined")
            {
                Log.Information("参数1！userId:{0}", userId.ToList()[0].ToString());
                Log.Information("参数2！type:{0}", type.ToList()[0].ToString());
                string uId = userId.ToList()[0].ToString();
                string tp = type.ToList()[0].ToString();
                string cl = classId.ToList()[0].ToString();

                //若是律师、律所或用户登录加入正常分组
                AddUser(uId, Convert.ToInt32(tp), Convert.ToInt32(cl));
            }
   
            return base.OnConnectedAsync();
        }

        /// <summary>
        /// 当连接断开时的处理
        /// </summary>
        public override Task OnDisconnectedAsync(Exception exception)
        {
            string connid = Context.ConnectionId;
            Log.Information("断开链接！cId:{0}", connid);
            //断开连接移除用户/客服
            var uList = new List<OnLinkUserDTO>();

            //OLCSUserList.OLUList = OLCSUserList.OLUList.IsNullOrEmpty() ? new List<OnLinkUserDTO>() : OLCSUserList.OLUList;
            //var offsList = OLCSUserList.OLUList.Where(x => x.Connid.Equals(connid)).ToList();
            //if (offsList.Count > 0)
            //{
            //    var offList = JsonConvert.DeserializeObject<List<OnLinkUserDTO>>(offsList.ToJson());
            //    foreach (var item in offList)
            //    {
            //        var index = OLCSUserList.OLUList.IndexOf(item);
            //        Log.Information("客服移除第{0}");
            //        if (index>=0)
            //        {
            //            OLCSUserList.OLUList.RemoveAt(index);
            //        }
            //    }
            //}

            var cache = _serviceProvider.GetService<IDistributedCache>();
            var jstr = cache.GetString("OLinkUserList");
            if (!jstr.IsNullOrEmpty())
            {
                //移除本链接客服
                uList = JsonConvert.DeserializeObject<List<OnLinkUserDTO>>(jstr);
                var sTime = DateTime.Now.AddHours(-1);
                //查询断开链接登录用户和链接超过一个小时没刷新用户
                var usList = uList.Where(x => x.Connid.Equals(connid) || x.CreateTime < sTime).ToList();
                if (usList.Count  > 0)
                {
                    foreach (var item in usList)
                    {
                        uList.Remove(item);
                    }
                    cache.SetString("OLinkUserList", uList.ToJson().ToString());
                }

                //if (usList.Count > 0)
                //{

                //    var sList = JsonConvert.DeserializeObject<List<OnLinkUserDTO>>(usList.ToJson());


                //    foreach (var item in sList)
                //    {
                //        var index = uList.IndexOf(item);
                //        Log.Information("移除第{0}个客服，uid={1}",index,item.UserId);
                //        if (index>=0)
                //        {
                //            uList.RemoveAt(index);
                //        }
                //    }

                //    //插入新用户
                //    cache.SetString("OLinkUserList", uList.ToJson().ToString());
                //}
            }

            return base.OnDisconnectedAsync(exception);
        }

    }
}
